package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.*;

public class RolDao extends BaseDao {
	private ResultSet rolID;
	private static RolDao rolDao=null;
	private List<Rol> roles;

	private RolDao(){}
	public static RolDao getRolDao(){
		if (rolDao == null) {
			rolDao = new RolDao();
			}
			return rolDao;
	}
	@Override
	public Rol buscar(Integer id) {
		try {
			String sqlSent = "SELECT * FROM rol WHERE id=" + id;
			rolID = consultar(sqlSent);
			if (rolID.next()) {
				Rol rol = new Rol(id,rolID.getString("nombre"));
				desconectar();
				return rol;
			} else {
				Rol rol = null;
				return rol;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Rol rol = null;
			try {
				desconectar();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return rol;
		}
	}
	@Override
	public List<Rol> listar() {
		ArrayList<Rol> list = new ArrayList<Rol>();
		try {
			String sqlSent = "SELECT * FROM rol";
			rolID = consultar(sqlSent);
			while (rolID.next()) {
				Rol rol = new Rol(rolID.getInt("id"),rolID.getString("nombre"));
				list.add(rol);
			}
			desconectar();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		roles = list;
		return roles;
	}
	@Override
	public void guardar(Object rol)throws SQLException {
		String sqlSent = "INSERT INTO rol (`nombre`) VALUES ('"
				+ ((Rol) rol).getNombre() + "')";
		try {
			modificar(sqlSent);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new SQLException("Error al guardar el rol");
		}
	}
	@Override
	public void eliminar(Integer id)throws SQLException {
		String sqlSent = "DELETE FROM rol WHERE id=" + id;
		try {
			modificar(sqlSent);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new SQLException("Error al borrar el rol");
		}
	}
	@Override
	public void modificar(Object rol)throws SQLException {
		String sqlSent = "UPDATE rol SET nombre='" + ((Rol) rol).getNombre()
				+ "' WHERE id=" + ((Rol) rol).getId();
		try {
			modificar(sqlSent);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new SQLException("Error al modificar el rol");
		}
	}
}
